<?php
class newYearController extends appController
{
	public function set()
	{
		$_SESSION['wxid']=$_GET['wxid'];
	}
	public function setYaoWxid()
	{
		$_SESSION['yaoWxid']=$_GET['wxid'];
		echo "赋值成功";
	}
	//清除数据
	public function clear()
	{
		unset($_SESSION['wxid']);
		unset($_SESSION['yaoWxid']);
		echo "已清除数据";
		exit;
	}
	//微信访问地址
	public function index()
	{
		if(!isset($_SESSION['wxid']))
		{
			//是否已授权
			$this->check_member();
		}
		else
		{
			$m = Model('newYear');
			//微信分享参数构建
			$jsdk = $m ->get_jsdk();
			$this->assign("signPackage", $jsdk);
			
			$config[c] = array('site_name' => "G4跨年晚会");
			$this->assign_global($config);
			$this->display('index.html');
		}
	}
	//微信访问地址
	public function indexZB()
	{
		if(!isset($_SESSION['wxid']))
		{
			//是否已授权
			$this->check_member();
		}
		else
		{
			$m = Model('newYear');
			//微信分享参数构建
			$jsdk = $m ->get_jsdk();
			$this->assign("signPackage", $jsdk);
			
			$config[c] = array('site_name' => "G4跨年晚会");
			$this->assign_global($config);
			$this->display('indexZB.html');
		}
	}
	//需要授权才可进入游戏
	public function canIn($wxid)
	{
		if(!$wxid>0)
		{
			header("Location:http://".$_SERVER['HTTP_HOST']."/ws/index.php?g=home&m=chat&a=index");
			exit;
		}
	}
	
	public function activity()
	{
		//当前用户的微信id
		$wxid = $_SESSION['wxid']?$_SESSION['wxid']:0;
		$this->canIn($wxid);
		$m = Model('newYear');
		//微信分享参数构建
		$jsdk = $m ->get_jsdk();
		$this->assign("signPackage", $jsdk);
		
		//
		$vote = $m->getVote();
		$this->assign("vote", $vote);
		
		$info = $m->getVoteAndWXInfo($wxid);
		$this->assign("info", $info);
// 		$zbActivity = $m->getNewYearZBActivity();
		$path = ROOT_PATH."zbActivity.json";
		$zbActivity = file_get_contents($path);
		$this->assign("zbActivity", $zbActivity);
		//系统时间戳
		$this->assign("nowTime", yf_time());
		$config[c] = array('site_name' => "G4跨年晚会");
		$this->assign_global($config);
		$this->display('activity.html');
	}
	
	public function sendVote()
	{
		$result = array("error"=>1,"content"=>"请刷新页面后重新登录");
		//当前用户的微信id
		$wxid = $_SESSION['wxid']?$_SESSION['wxid']:0;
		if(!$wxid>0)
		{
			$this->showMsg($result);
		}
		$info['vote'] = isset($_POST['vote'])?intval($_POST['vote']):1;
		$info['wxid'] = $wxid;
		$res = Model('newYear')->sendVote($info);
		if($res)
		{
			$result["error"]=0;
			$result["status"]=$res['status'];
			$result['vote'] = $res['vote'];
			$result["content"]="投票成功";
		}else{
			$result["error"]=1;
			$result["content"]="投票失败";
		}
		$this->showMsg($result);
	}
	
	public function getZBHongbao(){
		$m = Model('newYear');
		$openid = $m->get_openid($_POST['wxid']);
		if(!$openid){
			$res['error'] = 1;
			$res['content'] = "请重新登录";
			die(json_encode($res));
		}
		$voteId = $m->isVote($_POST['wxid']);
		if(!$voteId){
			$res['error'] = 1;
			$res['content'] = "投票后方可抢红包";
			die(json_encode($res));
		}
		$noncestr = hy_rand(28);
		$lottery_id =$m->getZBLottery($_POST['zbhb_id']);
		$post_data = array(
				"lottery_id"=>$lottery_id,
				"noncestr"=>$noncestr,
				"openid"=>$openid,
		);
		$path = ROOT_PATH."Admin/Config/ZB.json";
		$data = json_decode(file_get_contents($path), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$res['result'] = $post_data;
		print_r(json_encode($res));
	}
	
// 	private function ToUrlParams($urlObj)
// 	{
// 		//sort($urlObj);
// 		$buff = "";
// 		foreach ($urlObj as $k => $v)
// 		{
// 			if($k != "sign"){
// 				$buff .= $k . "=" . $v . "&";
// 			}
// 		}
	
// 		$buff = trim($buff, "&");
// 		return $buff;
// 	}
	
	public function refreshActivity()
	{
// 		$m = Model('newYear');
		$path = ROOT_PATH."zbActivity.json";
		$zbActivity = file_get_contents($path);
		if($zbActivity){
			$res['error'] = 0;
			$res['data'] = $zbActivity;
		}else{
			$res['error'] = 1;
		}
		print_r(json_encode($res));
	}
	
	
	//yaotv
	public function getWxid()
	{
		if(!isset($_SESSION['yaoWxid'])){
			$access_token = $this->getYaoAccessToken();
			$path = ROOT_PATH."Admin/Config/yaotv.json";
			$data = json_decode(file_get_contents($path), true);
			$appid = $data['yaoappid'];
			$user_info = $this->return_user_info($appid, $access_token, $_REQUEST['code']);
			if(!isset($user_info['openid'])){
				$res['error'] = 1;
				$res['content'] = "请重新登录";
				unset($_SESSION['yaoWxid']);
				die($_REQUEST['callback']."(".json_encode($res).")");
			}
			$a = Model('app');
			$m = Model('newYear');
			$check_openid = $a->get_count_openid($user_info['openid']);
			if($check_openid == 0)
			{
				$info['openid'] = $user_info['openid'];
				$info['nickname'] = $user_info['nickname'];
				$info['sex'] = $user_info['sex'];
				$info['headimgurl'] = $user_info['headimgurl']."/64";
				$wxid =$a->insert_into_wxuser($info);
				if(!$wxid)
				{
					echo "System Error! Please wait for a while!";
				}
			}
			else
			{
				$wxid = $a->get_wxid($user_info['openid']);
			}
			$_SESSION['yaoWxid'] = $wxid;
			//当前用户的微信信息
			$info = $m->getVoteAndWXInfo($_SESSION['yaoWxid']);
			$res['error'] = 0;
			$res['data'] = $info;
			$res['status'] = "CODE";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}else{
			//当前用户的微信信息
			$m = Model('newYear');
			$info = $m->getVoteAndWXInfo($_SESSION['yaoWxid']);
			$res['error'] = 0;
			$res['status'] = "SESSION";
			$res['data'] = $info;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
	}
	
	public function return_user_info($appid,$access_token,$code){
		$url = "https://api.weixin.qq.com/yaotv/user/userinfo?appid=".$appid."&access_token=".$access_token."&code=".$code;
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		$this->write_log($arr['openid'], $code);
		return $arr;
	}
	
	public function write_log($openid,$code){
		$file = ROOT_PATH."Qiaqia/Log/tv_err.log";
		$content = "wxid：".date("Y-m-d H:i:s").": code:".$code." openid:".$openid.PHP_EOL;
		$f  = file_put_contents($file, $content,FILE_APPEND);
	}
	
	public function getTvActivity()
	{
		$m = Model('newYear');
		$path = ROOT_PATH."tvActivity.json";
		$tvActivity = file_get_contents($path);
// 		$zbActivity = $m->getNewYearTVActivity();
		$vote = $m->getVote();
		if($tvActivity){
			$res['error'] = 0;
			$res['nowTime'] = yf_time();
			$res['data'] = $tvActivity;
			$res['vote'] = $vote;
		}else{
			$res['error'] = 1;
		}
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	public function sendTvVote()
	{
		$result = array("error"=>1,"content"=>"请刷新页面后重新登录");
		//当前用户的微信id
		$wxid = intval($_REQUEST['wxid'])>0?intval($_REQUEST['wxid']):0;
		if(!$wxid>0)
		{
			die($_REQUEST['callback']."(".json_encode($result).")");
		}
		$info['vote'] = isset($_GET['vote'])?intval($_GET['vote']):1;
		$info['wxid'] = $wxid;
		$res = Model('newYear')->sendVote($info);
		if($res)
		{
			$result["error"]=0;
			$result['vote'] = $res['vote'];
			$result["status"]=$res['status'];
			$result["content"]="投票成功";
		}else{
			$result["error"]=1;
			$result["content"]="投票失败";
		}
		die($_REQUEST['callback']."(".json_encode($result).")");
	}
	
	public function getTVHongbao(){
		$m = Model('newYear');
		$openid = $m->get_openid($_GET['wxid']);
		if(!$openid){
			$res['error'] = 1;
			$res['content'] = "请重新登录";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$voteId = $m->isVote($_GET['wxid']);
		if(!$voteId){
			$res['error'] = 1;
			$res['content'] = "投票后方可抢红包";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$isGetHB = $m->isGetHB($_GET['status']);
		if(!$isGetHB){
			$res['error'] = 1;
			$res['content'] = "本轮抢红包活动已结束";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$noncestr = hy_rand(28);
		$lottery_id =$m->getTVLottery($_GET['tvhb_id']);
		$post_data = array(
				"lottery_id"=>$lottery_id,
				"noncestr"=>$noncestr,
				"userid"=>$openid,
		);
		$path = ROOT_PATH."Admin/Config/yaotv.json";
		$data = json_decode(file_get_contents($path), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$res['result'] = $post_data;
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function saveHongbaoInfo(){
		$m = Model('newYear');
		$info['wxid'] = isset($_GET['wxid'])?$_GET['wxid']:$_SESSION['yaoWxid'];
		$info['hongbao_id']  = $_GET['hongbao_id'];
		$info['addtime'] = $_SERVER['REQUEST_TIME'];
		$id = $m->insert($info,"get_hongbao_user");
	}
	public function getYaoAccessToken(){
		$path = ROOT_PATH."Qiaqia/Json/yao_access_token.json";
		$data = json_decode(file_get_contents($path), true);
		if(empty($data['access_token']) || $data['expire_time'] < yf_time()){
	
			$path2 = ROOT_PATH."Admin/Config/yaotv.json";
			$data2 = json_decode(file_get_contents($path2), true);
			$app['appid'] = $data2['yaoappid'];
			$app['appsecret'] = $data2['yaoappSecret'];
			$new_info = $this->getToken($app['appid'], $app['appsecret']);
			$info['access_token'] = $new_info['access_token'];
			$info['expire_time'] = yf_time() + 1500;
			$fp = fopen($path, "w");
			fwrite($fp, json_encode($info));
			fclose($fp);
			return $new_info['access_token'];
		}else{
			return $data['access_token'];
		}
	}
	
	public function getToken($appid,$secret){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		$token = json_decode($result);
		$yf_info['access_token'] = $token->access_token;
		$yf_info['expires_in'] = $token->expires_in;
		return $yf_info;
	}
	public function refreshTvActivity()
	{
		$path = ROOT_PATH."tvActivity.json";
		$zbActivity = file_get_contents($path);
		if($zbActivity){
			$res['error'] = 0;
			$res['data'] = $zbActivity;
		}else{
			$res['error'] = 1;
		}
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function lastHongbao()
	{
		$m = Model('newYear');
		$openid = $m->get_openid($_GET['wxid']);
		if(!$_GET['wxid']||!$openid){
			$res['error'] = 1;
			$res['content'] = "很遗憾，没有抢到红包!";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$status = $m->get_cfg("lastHB");
		if(!$status){
			$res['error'] = 1;
			$res['content'] = "很遗憾，没有抢到红包...";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		switch ($status)
		{
			case 1:$tvhb_id = 30;break;
			case 2:$tvhb_id = 31;break;
// 			case 3:$tvhb_id = 32;break;
			case 4:$tvhb_id = 32;break;
			case 5:$tvhb_id = 33;break;
			case 6:$tvhb_id = 34;break;
			default:$tvhb_id = 35;break;
		}
		$lottery_id =$m->getTVLottery($tvhb_id);
		$noncestr = hy_rand(28);
		$post_data = array(
				"lottery_id"=>$lottery_id,
				"noncestr"=>$noncestr,
				"userid"=>$openid,
		);
		$path = ROOT_PATH."Admin/Config/yaotv.json";
		$data = json_decode(file_get_contents($path), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$res['HB_id'] = $tvhb_id;
		$res['result'] = $post_data;
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function pushError()
	{
		$file = ROOT_PATH."Qiaqia/Log/tv_err.log";
		$content = "code：".date("Y-m-d H:i:s").": errorCode:".$_GET['errorCode']." errorMsg:".$_GET['errorMsg'].PHP_EOL;
		$f  = file_put_contents($file, $content,FILE_APPEND);
	}
	
}